<template>
  <div class="container">
    <topTitle
      :titleText="titleText"
      :back="back"
      @gobackTriser="goBack"
    ></topTitle>
    <div class="mainCon noTitleExplain">
      <el-form
        :model="formData"
        label-width="165px"
        :rules="formRules"
        ref="formData"
        class="form"
      >
        <div :class="type == 'BAD' ? 'badFormBox formBox' : 'formBox'">
          <el-row class="row-padding-bottom" :gutter="100">
            <el-col :span="12" class="col-position">
              <el-form-item label="发生企业：" prop="companyName">
                <el-select
                  v-model="formData.uscc"
                  filterable
                  class="sWidth"
                  placeholder="请选择"
                  clearable
                  :popper-append-to-body="false"
                  v-if="loginType == 'JC'"
                  @change="selectCompany"
                >
                  <el-option
                    v-for="item in companyList"
                    :key="item.uscc"
                    :label="item.name"
                    :value="item.uscc"
                  ></el-option>
                </el-select>
                <el-input
                  v-model="formData.companyName"
                  placeholder="请输入企业名称"
                  disabled
                  v-else
                  class="sWidth"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12" class="col-position">
              <el-form-item label="统一社会信用代码：" prop="uscc">
                <el-input
                  class="sWidth"
                  v-model="formData.uscc"
                  placeholder="请输入"
                  @blur="formData.uscc = changeValue($event)"
                  disabled
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row class="row-padding-bottom" :gutter="100">
            <el-col :span="12" class="col-position">
              <el-form-item label="是否发生在工程项目：" prop="isProject">
                <el-radio-group
                  class="sWidth"
                  v-model="formData.isProject"
                  :disabled="isProjectDisabled"
                  @change="changeIsProject"
                >
                  <el-radio :label="1">是</el-radio>
                  <el-radio :label="0">否</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="12" class="col-position">
              <el-form-item label="发生项目：" prop="projectId">
                <el-select
                  class="sWidth"
                  v-model="formData.projectId"
                  clearable
                  filterable
                  :placeholder="
                    loginType == 'JC' && !formData.uscc
                      ? '请先选择企业'
                      : '请选择'
                  "
                  :disabled="selectedProject"
                  @change="selectProject"
                >
                  <el-option
                    v-for="(item, index) of projectList"
                    :key="index"
                    :label="item.name"
                    :value="item.code"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row class="row-padding-bottom" :gutter="100">
            <el-col :span="12" class="col-position">
              <el-form-item label="人员姓名：" prop="name">
                <el-select
                  class="sWidth"
                  v-model="formData.idcard"
                  clearable
                  filterable
                  :disabled="selectedName"
                  :placeholder="
                    loginType == 'JC' &&
                    !formData.projectId &&
                    formData.isProject == '1'
                      ? '请先选择发生工程'
                      : '请选择'
                  "
                  @change="selectPeople"
                >
                  <el-option
                    v-for="(item, index) of peopleList"
                    :key="index"
                    :label="item.name"
                    :value="item.idcard"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12" class="col-position">
              <el-form-item label="身份证号：" prop="idcard">
                <el-input
                  class="sWidth"
                  v-model="formData.idcard"
                  placeholder="请输入"
                  disabled
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row class="row-padding-bottom" :gutter="100">
            <el-col :span="12" class="col-position">
              <el-form-item label="发生时间：" prop="occurrenceDate">
                <el-date-picker
                  class="sWidth"
                  v-model="formData.occurrenceDate"
                  type="date"
                  :picker-options="pickerOptions"
                  value-format="yyyy-MM-dd"
                  placeholder="选择日期"
                >
                </el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="12" class="col-position">
              <el-form-item label="人员职位：" prop="position">
                <el-input
                  class="sWidth"
                  v-model="formData.position"
                  placeholder="请输入"
                  @blur="formData.position = changeValue($event)"
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row class="row-padding-bottom">
            <el-col :span="24" class="col-position">
              <el-form-item
                :label="this.type == 'BAD' ? '详细记录：' : '奖励说明：'"
                prop="description"
              >
                <el-input
                  v-model="formData.description"
                  :rows="5"
                  type="textarea"
                  :placeholder="
                    this.type == 'BAD'
                      ? '请描述事件的详细情况，事件的不良影响等'
                      : '请描述奖励详细情况'
                  "
                >
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24" class="col-position">
              <el-form-item
                label="上传资料："
                prop="upLoadFile"
                v-model="formData.fileList"
              >
                <uploadAnnex
                  :limitationFactor="limitationFactor"
                  @getFile="getFile"
                  :upLoadFile="upLoadFile"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row v-if="upLoadFile.length > 0">
            <el-col :span="24" v-model="formData.fileList">
              <uploadResult
                style="margin-left: 120px"
                :resultList="upLoadFile"
                @callBackResult="getFile"
              />
            </el-col>
          </el-row>
        </div>
        <el-row v-if="type == 'BAD'">
          <el-col :span="24" class="col-position" style="margin-top: 20px">
            <el-form-item label="" prop="isRead" label-width="0" class="btnBox">
              <el-checkbox v-model="isRead">我已阅读并知晓</el-checkbox>
              <el-link type="primary" @click="toRead"
                ><<不良记录添加承诺书>></el-link
              >
            </el-form-item>
          </el-col>
        </el-row>
        <div class="btnBox">
          <el-button class="commonBut saveBtn" @click="toSave" :loading="isAdd"
            >保存</el-button
          >
          <el-button class="commonBut" @click="goBack">取消</el-button>
        </div>
      </el-form>
      <!-- 弹窗 -->
      <el-dialog
        title="不良记录添加承诺书"
        :visible.sync="dialogFormVisible"
        :close-on-click-modal="false"
        :show-close="false"
        width="750px"
        :modal-append-to-body="false"
        :append-to-body="true"
      >
        <div class="dialogContent">
          本人/企业郑重承诺，填写的不良记录情况全部属实，提供的材料真实有效。如有不实之处，愿负相应的法律责任，并承担由此产生的一切后果
        </div>
        <div slot="footer" class="dialog-footer">
          <el-button @click="cancelDialog" class="cancel">取 消</el-button>
          <el-button type="primary" class="save" @click="affirm"
            >已知晓</el-button
          >
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>
export default {
  name: 'addRecord',
  data() {
    var checkUpLoadFile = (rule, value, callback) => {
      var that = this
      if (that.upLoadFile.length == 0) {
        return callback(new Error('资料不能为空'))
      } else {
        callback()
      }
    }
    var checkUscc = (rule, value, callback) => {
      var that = this
      if (!that.formData.companyName || !that.formData.uscc) {
        return callback(new Error('发生企业不能为空'))
      } else {
        callback()
      }
    }
    return {
      back: true,
      titleText: '',
      formData: {
        type: '', //奖励GOOD，不良BAD
        id: '',
        employeeId: '',
        companyName: '', //发生企业
        uscc: '', //统一社会信用代码
        isProject: '', //是否发生在工程项目
        projectId: '', //发生工程
        projectName: '', //项目名称
        name: '', //人员姓名
        idcard: '', //身份证号
        occurrenceDate: '', //发生时间
        position: '', //人员职务
        description: '', //详细记录
        fileList: '', //附件
      },
      //验证
      formRules: {
        companyName: [
          {
            required: true,
            message: '请输入企业名称',
            // trigger: "blur",
            validator: checkUscc,
          },
        ],
        uscc: [
          {
            required: true,
            message: '请输入统一社会信用代码',
            // trigger: "blur",
          },
        ],
        isProject: [
          {
            required: true,
            message: '请选择',
            trigger: 'change',
          },
        ],
        name: [
          {
            required: true,
            message: '请选择人员姓名',
            trigger: 'change',
          },
        ],
        idcard: [
          { required: true, message: '请输入身份证号', trigger: 'blur' },
        ],
        projectId: [
          { required: true, message: '请选择发生项目', trigger: 'change' },
        ],
        occurrenceDate: [
          { required: true, message: '请选择发生时间', trigger: 'change' },
        ],
        position: [
          { required: true, message: '请输入人员职位', trigger: 'blur' },
        ],
        description: [
          { required: true, message: '请输入详细记录', trigger: 'blur' },
          {
            min: 1,
            max: 300,
            message: '最多仅支持300字',
            trigger: 'blur',
          },
        ],
        upLoadFile: [
          {
            required: true,
            validator: checkUpLoadFile,
            trigger: 'blur',
          },
        ],
      },
      companyList: [],
      // 项目列表
      projectList: [],
      // 人员列表
      peopleList: [],
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() > Date.now()
        },
      },
      id: '',
      type: '', //编辑还是添加
      isAdd: false,
      //附件
      limitationFactor: {
        uploadAnnexUrl: 'api-f/files/upload', //自定义上传文件接口地址
        upLoadFileLength: 10, //自定义上传附件的个数设置
        fileSize: 5, //自定义上传文件最大设置
        formatType: 'typeFour', //自定义上传格式校验类型
        messagetip: '仅支持上传png、jpg、jpeg格式文件', //自定义报错提示语
        fileId: 'file', //自定义id解决一个页面包含多个上传附件
        uploadFormId: 'salaryExcelInsuranceForm', //自定义id解决一个页面包含多个上传附件
        messagetip:
          '上传格式支持png，jpg，jpeg，doc，docx，xls，xlsx，pdf，附件大小不超过5M，最多上传10个附件', //自定义报错提示语
        methodTip:
          '上传格式支持png，jpg，jpeg，doc，docx，xls，xlsx，pdf，附件大小不超过5M，最多上传10个附件', //自定义上传文件提示
        uploadBtnType: 'typeOne', //自定义上传按钮类型
      },
      upLoadFile: [],
      userType: '', //用户类型，企业用户还是项目用户
      isProjectDisabled: false, //是否发现项目能否编辑
      selectedProject: false,
      dialogFormVisible: false, //不良记录添加承诺书弹窗
      isRead: false,
      isEdit: '', //是否是编辑页
      loginType: '',
      selectedName: false,
    }
  },
  async created() {
    this.id = this.$route.query.id
    this.type = this.$route.query.type
    this.formData.type = this.type
    this.isEdit = this.$route.query.isEdit
    this.loginType = window.localStorage.getItem('loginType')
    if (this.isEdit === 'true') {
      if (this.type == 'BAD') {
        this.titleText = '编辑不良记录'
        this.isRead = true
        this.selectedName = true
      } else {
        this.titleText = '编辑奖励记录'
      }
      this.formData.id = this.id
      this.getDetail()
    } else {
      if (this.type == 'BAD') {
        this.titleText = '添加不良记录'
      } else {
        this.titleText = '添加奖励记录'
        this.formRules.description[0].message = '请输入奖励说明'
      }
    }
    //企业用户还是项目用户
    this.userType = this.$store.state.userType
    // if (this.loginType != "JC") {
    //   this.getProjects();
    // }
    this.getCompanyList()

    this.changeIsProject()
  },

  methods: {
    // 切换是否发生在项目
    changeIsProject(val) {
      //项目用户，是否发生项目默认为是，不可更改
      this.peopleList = []
      this.formData.idcard = ''
      if (this.loginType == 'JC') {
        this.formData.isProject = ''
        this.selectedProject = false
        this.formData.projectId = ''
        this.formData.projectName = ''

        if (val == 1) {
          this.selectedProject = false
          this.formData.isProject = val
          this.formRules.projectId[0].required = true
        } else {
          this.selectedProject = true
          this.formData.isProject = val
          this.formData.projectId = ''
          this.formData.projectName = ''
          this.formRules.projectId[0].required = false
          this.getEmployees()
        }
        return
      }
      this.getProjects()
      if (this.userType == 'PROJECT_ADMINISTRATOR') {
        this.formData.isProject = 1
        this.isProjectDisabled = true
        this.selectedProject = true
        this.formRules.projectId[0].required = true
      } else {
        if (this.isEdit === 'true' && this.type == 'BAD') {
          this.isProjectDisabled = true
        } else {
          this.isProjectDisabled = false
        }
        if (!val) {
          this.formData.isProject = 0
          this.selectedProject = true
          this.formData.projectId = ''
          this.formData.projectName = ''
          this.formRules.projectId[0].required = false
          return
        }
        if (val == 1) {
          this.selectedProject = false
          this.formData.isProject = val
          this.formRules.projectId[0].required = true
        } else {
          this.selectedProject = true
          this.formData.isProject = val
          this.formData.projectId = ''
          this.formData.projectName = ''
          this.formRules.projectId[0].required = false
        }
      }
    },
    getCompanyList() {
      this.axios({
        method: 'post',
        url: 'api-c/company/expand/monitor/companylist',
        data: {
          type:
            localStorage.getItem('judgeRoleCode') == 'project' ? 'CS' : 'NC', //非建传NC，建筑传CS
        },
      }).then((resp) => {
        if (!resp.data.hasError) {
          this.companyList = resp.data.result
        }
      })
    },
    // 获取当前企业
    getCurrentcompany() {
      this.axios({
        method: 'post',
        url: 'api-c/company/expand/currentcompany',
        data: {
          projectId: this.formData.projectId,
        },
      }).then((resp) => {
        if (!resp.data.hasError) {
          this.formData.companyName = resp.data.result.companyName
          this.formData.uscc = resp.data.result.uscc
        }
      })
    },
    // 获取企业下面的人员
    getEmployees(projectId) {
      this.axios({
        method: 'post',
        url: 'api-e/cs/employee/expand/employees',
        data: {
          projectId: projectId ? projectId : this.formData.projectId,
          // projectId: "2c9045426f12787b016f17dbaf8f0003",
          uscc: this.formData.uscc,
          name: '',
        },
      }).then((resp) => {
        if (!resp.data.hasError) {
          this.peopleList = resp.data.result
        }
      })
    },
    // 选择单位
    selectCompany(uscc) {
      // 获取项目列表
      this.companyList.forEach((item) => {
        if (item.uscc == uscc) {
          this.formData.companyName = item.name
        }
      })
      this.formData.projectId = ''
      this.formData.projectName = ''
      console.log(this.formData.isProject)
      if (this.formData.isProject === 0) {
        // 人员数据清空
        this.formData.name = ''
        this.formData.idcard = ''
        this.getEmployees()
      }
      this.getProjectList(uscc)
    },
    getProjectList(uscc) {
      this.axios({
        method: 'post',
        url: 'api-p/projectcompany/base/findprojectbyuscc',
        data: {
          uscc: uscc,
          // uscc: "91110000710924929L",
        },
      }).then((resp) => {
        if (!resp.data.hasError) {
          this.projectList = resp.data.result
        }
      })
    },
    // 选择人员
    selectPeople(value) {
      this.peopleList.forEach((item) => {
        if (item.idcard == value) {
          this.formData.name = item.name
          this.formData.employeeId = item.id
        }
      })
      // this.formData.idcard =
    },
    // 选择项目
    selectProject(value) {
      this.projectList.forEach((item) => {
        if (item.code == value) {
          this.formData.projectName = item.name
        }
      })
      // 人员数据清空
      this.formData.name = ''
      this.formData.idcard = ''
      // 获取人员
      this.getEmployees(value)
    },
    getProjects() {
      this.axios({
        method: 'post',
        url: 'api-p/projectcompany/expand/current/projects',
        data: {
          sysAppCode: localStorage.getItem('judgeRoleCode'),
        },
      }).then((resp) => {
        if (!resp.data.hasError) {
          this.projectList = resp.data.result
          if (
            this.projectList.length &&
            this.userType == 'PROJECT_ADMINISTRATOR'
          ) {
            this.formData.projectId = resp.data.result[0].code
            this.formData.projectName = resp.data.result[0].name
          }
          if (this.loginType != 'JC') {
            this.getCurrentcompany()
          }

          this.getEmployees()
        }
      })
    },
    toSave() {
      this.isAdd = true
      this.$refs.formData.validate((valid) => {
        if (valid) {
          if (!this.isRead && this.type == 'BAD') {
            this.$message({
              message: '请勾选《不良记录添加承诺书》',
              type: 'warning',
            })
            this.isAdd = false
            return
          }
          this.save()
        } else {
          this.isAdd = false
        }
      })
    },
    save() {
      var url = ''
      if (this.isEdit == 'true') {
        url = 'api-r/employee/creditrecord/edit'
      } else {
        url = 'api-r/employee/creditrecord/add'
      }
      this.formData.fileList = JSON.stringify(this.upLoadFile)
      this.axios({
        method: 'post',
        url: url,
        data: this.formData,
      })
        .then(
          (response) => {
            if (!response.data.hasError) {
              var text = this.isEdit == 'true' ? '编辑成功' : '添加成功'
              this.$message({
                message: text,
                type: 'success',
              })

              if (
                this.isEdit != 'true' &&
                this.loginType == 'JC' &&
                this.type == 'BAD'
              ) {
                // 监察添加成功，跳转到编辑页面
                this.$router.push({
                  path: '/home/worker/badRecordDetail',
                  name: 'badRecordDetail',
                  query: {
                    id: response.data.result,
                    type: this.type,
                    operation: 'edit',
                  },
                })
                this.$store.commit('CHANGE_SLIDER_NAME', {
                  oldUrl: '/home/worker/badRecord',
                  newUrl: this.$router.currentRoute.fullPath,
                })
              } else {
                this.goBack()
              }
            } else {
              this.$message({
                message: response.data.errorMsg,
                type: 'error',
              })
            }
            this.isAdd = false
          },
          (response) => {
            this.isAdd = false
          }
        )
        .catch((error) => {
          this.isAdd = false
        })
    },
    //获取详情
    getDetail() {
      this.axios({
        method: 'post',
        url: 'api-r/employee/creditrecord/detail',
        data: { id: this.$route.query.id },
      })
        .then((response) => {
          if (!response.data.hasError) {
            // this.formData = response.data.result;
            var info = response.data.result
            this.formData.type = this.type //奖励GOOD，不良BAD
            this.formData.id = info.id
            this.formData.employeeId = info.employeeId
            this.formData.companyName = info.companyName //发生企业
            this.formData.uscc = info.uscc //统一社会信用代码
            this.formData.isProject = info.isProject //是否发生在工程项目
            this.formData.projectId = info.projectId //发生工程projectId
            this.formData.projectName = info.projectName //发生工程
            this.formData.name = info.name //人员姓名
            this.formData.idcard = info.idcard //身份证号
            this.formData.occurrenceDate = info.occurrenceDate //发生时间
            this.formData.position = info.position //人员职位
            this.formData.description = info.description //详细记录
            this.upLoadFile = response.data.result.fileList
            //是否发生在工程项目
            if (this.formData.projectId) {
              this.formData.isProject = 1
              if (this.userType != 'PROJECT_ADMINISTRATOR') {
                if (this.isEdit === 'true' && this.type == 'BAD') {
                  this.selectedProject = true
                } else {
                  this.selectedProject = false
                }
              }
            } else {
              this.formData.isProject = 0
            }
          } else {
            this.$message({
              message: response.data.errorMsg,
              type: 'error',
            })
          }
        })
        .catch((error) => {
          this.$message({
            showClose: true,
            duration: 3000,
            message: '获取数据失败',
            type: 'error',
          })
        })
    },
    getFile(val) {
      this.upLoadFile = val
    },
    //返回
    goBack() {
      var url = ''
      if (this.type == 'BAD') {
        //不良记录
        url = '/home/worker/badRecord'
      } else {
        //奖励记录
        url = '/home/worker/rewards'
      }
      this.$router.push(url)
      this.$store.commit('GOBACK_NAME', {
        oldUrl: url,
        newUrl: this.$router.currentRoute.fullPath,
      })
    },
    // 不良记录添加承诺书弹窗
    toRead() {
      this.dialogFormVisible = true
    },
    affirm() {
      this.isRead = true
      this.dialogFormVisible = false
    },
    cancelDialog() {
      this.dialogFormVisible = false
    },
  },
  watch: {
    upLoadFile(val) {
      if (val.length > 0) {
        this.$refs.formData.clearValidate('upLoadFile')
      }
    },
    'formData.name'(val) {
      if (val) {
        this.$refs.formData.clearValidate('idcard')
      }
    },
  },
}
</script>

<style scoped lang="less">
.mainCon {
  padding: 0;
}
.formBox {
  position: relative;
  padding: 40px 80px 0px 20px;
  overflow-y: auto;
  .sWidth {
    width: 100% !important;
  }
}
.badFormBox {
  &::after {
    position: absolute;
    right: 24px;
    bottom: 0;
    left: 24px;
    height: 1px;
    content: '';
    -webkit-transform: scaleY(0.5);
    transform: scaleY(0.5);
    background-color: #e3e7e9;
    z-index: 10;
  }
}
.btnBox {
  text-align: center;
  margin-bottom: 24px;
}
</style>
